package cn.iocoder.yudao.module.trade.api.order;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.trade.api.order.dto.DepositOrderDTO;
import cn.iocoder.yudao.module.trade.dal.dataobject.depositorder.DepositOrderDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.depositproductrelation.DepositProductRelationDO;
import cn.iocoder.yudao.module.trade.dal.mysql.depositorder.DepositOrderMapper;
import cn.iocoder.yudao.module.trade.dal.mysql.depositproductrelation.DepositProductRelationMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class DepositOrderApiImpl implements DepositOrderApi{
    @Resource
    private DepositOrderMapper depositOrderMapper;

    @Resource
    private DepositProductRelationMapper depositProductRelationMapper;

    @Override
    public Integer selectOrderByGasId(Long id) {
        LambdaQueryWrapper<DepositOrderDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DepositOrderDO ::getCrmMemberUserId , id );
        // 只计算 2已收款完成的押金押瓶总数
        wrapper.eq(DepositOrderDO ::getStatus, 2 );
        // 根据燃气户id查询所有押金
        List<DepositOrderDO> depositOrderDOS = depositOrderMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(depositOrderDOS)){
            return 0;
        }
        // 计算每个押金 钢瓶数量总和
        AtomicReference<Integer> sum = new AtomicReference<>(0);
        depositOrderDOS.forEach(x -> {

            LambdaQueryWrapper<DepositProductRelationDO> dto = new LambdaQueryWrapper<>();
            dto.eq(DepositProductRelationDO ::getDepositId, x.getId());
            sum.updateAndGet(v -> v + depositProductRelationMapper.selectList(dto).stream().mapToInt(DepositProductRelationDO::getSkuCount).sum());
        });
        return sum.get();
    }

    @Override
    public List<DepositOrderDTO> selectOrderByGasIdList(Long id) {
        LambdaQueryWrapperX<DepositOrderDO> order = new LambdaQueryWrapperX<>();
        order.eq(DepositOrderDO ::getCrmMemberUserId, id);
        // 只计算 2已收款完成的押金押瓶总数
        order.eq(DepositOrderDO ::getStatus, 2 );
        return BeanUtils.toBean(depositOrderMapper.selectList(order), DepositOrderDTO.class);
    }
}
